<template>
  <el-form
    ref="registerForm"
    :model="registerUser"
    label-width="100px"
    :rules="registerRules"
    class="registerForm sign-up-form"
  >
    <el-form-item label="用户名" prop="name">
      <el-input
        v-model="registerUser.name"
        placeholder="Enter Name ...."
      ></el-input>
    </el-form-item>

    <el-form-item label="邮箱" prop="email">
      <el-input
        v-model="registerUser.email"
        placeholder="Enter Email ...."
      ></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input
        type="password"
        v-model="registerUser.password"
        placeholder="Enter Password ..."
      ></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="password2">
      <el-input
        type="password"
        v-model="registerUser.password2"
        placeholder="Enter Password2 ..."
      ></el-input>
    </el-form-item>
    <el-form-item label="选择身份">
      <el-select v-model="registerUser.role">
        <el-option label="管理员" value="admin"></el-option>
        <el-option label="用户" value="user"></el-option>
        <el-option label="游客" value="visitor"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        class="submit-btn"
        @click="handleRegister('registerForm')"
        >注册</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { defineComponent, getCurrentInstance } from "vue";
import {useRouter} from 'vue-router'

export default defineComponent({
  props: {
    registerUser: {
      type: Object,
      requeired: true,
    },
    registerRules: {
      type: Object,
      requeired: true,
    },
  },
  setup(props:any) {
    const { ctx } = getCurrentInstance() as any;
    const router = useRouter()

    const handleRegister = (formName: string) => {
      ctx.$refs[formName].validate((valid: boolean) => {
        if (valid) {
          console.log(222)
          ctx.$refs[formName].$axios.post("/api/v1/auth/register",
          props.registerUser).then((res:any) => {
            ctx.$message.success('注册成功')
            // 路由跳转
            router.push('/')
          })
          
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };

    return { handleRegister };
  },
});
</script>

<style scoped>
/* // 注册表单样式 */
.registerForm {
  margin-top: 20px;
  background-color: #fff;
  padding: 20px 40px 20px 20px;
  border-radius: 5px;
  box-shadow: 0px 5px 10px #cccc;
}
.submit-btn {
  width: 100%;
}
</style>